package com.example.black.myapplication.pathlearn;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.example.black.myapplication.R;

/**
 * <pre>
 *     author : 28476
 *     e-mail : hao.wang@1hai.cn
 *     time   : 2019/01/16/10:11
 *     desc   : path 和 pathMeasure
 *     使用 android:hardwareAccelerated="false" 在manifest中关闭了硬件加速
 *     version: 1.0
 * </pre>
 */

public class PathView extends View {

    public static final String TAG = PathView.class.getSimpleName();
    private Paint paint;
    private int mViewHeight;
    private int mViewWidth;
    private Path path;
    private PathMeasure measure;
    private PathMeasure measure2;
    private Path dst;

    public PathView(Context context) {
        super(context);
        initConfig();
    }

    public PathView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initConfig();
    }

    public PathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mViewHeight = h;
        mViewWidth = w;
    }

    private void initConfig() {
        setLayerType(View.LAYER_TYPE_SOFTWARE,null);
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(10);
        dst = new Path();
        path = new Path();

    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(mViewWidth/2, mViewHeight/2);
        path.lineTo(0,mViewHeight/2);
        path.lineTo(mViewWidth/2,0);

        measure = new PathMeasure(path,false);
        measure2 = new PathMeasure(path,true);
        Log.i(TAG, "onDraw1: length "+measure.getLength());
        Log.i(TAG, "onDraw2: length "+measure2.getLength());

        canvas.drawPath(path,paint);

        path.reset();
        path.addRect(-100,-100,100,100,Path.Direction.CW);
        path.addRect(-50,-50,50,50,Path.Direction.CW);
        measure = new PathMeasure(path,false);
        float length = measure.getLength();
        boolean nextContour = measure.nextContour();
        float length2 = measure.getLength();
        canvas.drawPath(path,paint);
        Log.i(TAG, "length1:"+length);
        Log.i(TAG, "length2:"+length2);
        //getSegment 截取一部分
        dst.reset();
        measure.getSegment(0,200,dst,true);//startWithMoveTo false时，是否从上一个结束点开始画
        paint.setColor(getResources().getColor(R.color.md_amber_400));
        canvas.drawPath(dst,paint);
        //getPosTan
    }
}
